import axios from 'axios'
import { BASE_URL } from '@/request/hostConfig'

const service = axios.create({
  baseURL: BASE_URL
})

service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    openErrorConfirmDialog(error.message || 'Error')
    
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const { status, statusText } = response
    const { code, msg, message = msg } = response.data
    
    if (status !== 200 || code !== 1) {
      const errorMessage = status === 200 ? message : statusText
      
      openErrorConfirmDialog(errorMessage || 'Error')
      
      return Promise.reject(new Error(errorMessage || 'Error'))
    }
    else {
      return response.data
    }
  },
  error => {
    openErrorConfirmDialog(error.message || 'Error')
    
    return Promise.reject(error)
  }
)

function openErrorConfirmDialog(message) {
  showConfirmDialog({
    title: '错误提示',
    message,
    confirmButtonText: '确定',
    showCancelButton: false
  })
}

export default service